package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("spit")
public class SpitController {
    @Autowired
    private SpitService spitService;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.查询吐槽列表
    @GetMapping
    public Result findAll(){
        List<Spit> spitList = spitService.findAll();
        return new Result(true,StatusCode.OK,"成功",spitList);
    }
    //2. 据id查询
    @GetMapping("{spitId}")
    public Result findById(@PathVariable String spitId){
        Spit spit = spitService.findById(spitId);
        return new Result(true,StatusCode.OK,"成功",spit);
    }

    //3. 添加吐槽数据
    @PostMapping
    public Result add(@RequestBody Spit spit){
        spitService.add(spit);
        return new Result(true,StatusCode.OK,"成功");
    }
    //4. 据id删除数据
    @DeleteMapping("{spitId}")
    public Result dele(@PathVariable String spitId){
        spitService.dele(spitId);
        return new Result(true,StatusCode.OK,"成功");
    }
    //5. 据id更新数据
    @PutMapping("{spitId}")
    public Result update(@RequestBody Spit spit,@PathVariable String spitId){
        //5.1 将spitId与spit绑定
        spit.set_id(spitId);
        spitService.update(spit);
        return new Result(true,StatusCode.OK,"成功");
    }
    //6.吐槽点赞
    @PutMapping("thumbup/{spitId}")
    public Result thumbup2(@PathVariable String spitId){
        //6.1 避免重复点赞
        //6.1.1 先从redis中取出标记
        Object o = redisTemplate.opsForValue().get("thumbup_" + spitId);
        //6.2 判断标记是否存在，存在就证明点赞了
        if (o != null){
            return new Result(false,StatusCode.ERROR,"不能重复点赞");
        }
        spitService.thumbup(spitId);
        redisTemplate.opsForValue().set("thumbup_" + spitId,"1");
        return new Result(true,StatusCode.OK,"成功");
    }
/*    //7. 根据parentId查询分页
    @GetMapping("{parentid}/{}/{size}")
    public Result findByParentId(@PathVariable String parentid, @PathVariable int page, @PathVariable int size){
       PageResult pageRequest = spitService.findByParentId(parentid,page,size);
        return new Result(true,StatusCode.OK,"成功",pageRequest);

    }*/

    //7. 根据parentid分页查询
    @GetMapping("comment/{parentid}/{page}/{size}")
    public Result findByParentid(@PathVariable String parentid,@PathVariable int page,@PathVariable int size){
        PageResult pageResult = spitService.findByParentid(parentid,page,size);
        return new Result(true,StatusCode.OK,"chenggong",pageResult);
    }
}
